const loki = require('lokijs')
const fs = require('fs')
const request = require('superagent');
// 启动log
const log4js = require('log4js');
log4js.configure({
    appenders: {
        cheese: {
            type: 'file',
            filename: './avatarFaile.log'
        }
    },
    categories: {
        default: {
            appenders: ['cheese'],
            level: 'trace'
        }
    }
});
const logger = log4js.getLogger('cheese');


var db = new loki('./SD_DB.db', {
    autoload: true,
    autoloadCallback: databaseInitialize,
    autosave: true,
    serializationMethod: 'pretty',
    autosaveInterval: 4000
});

// implement the autoloadback referenced in loki constructor
function databaseInitialize() {
    var robots = db.getCollection("robots");
    if (robots === null) {
        robots = db.addCollection("robots");
    }
    // kick off any program logic or start listening to external events
    runProgramLogic3(robots);
}


function createRobotDB(robots) {
    var robotJSON = JSON.parse(fs.readFileSync('./SDdata.json'))
    robots.insert(robotJSON)
}

let machineMap = {}
let madchineArr = []

function runProgramLogic(robots) {
    let res = robots.find({})
    console.log(`已加载${res.length}条数据库内容`)
    var i = 0
    getPic(i)

    function getPic(i) {
        let num = res[i].ID;
        request.get(`https://www.olgame.tw/sds/images/robot/${num}.gif`)
            .then(res => {
                // let num = robotpicPath.match(/\d+\.gif/)
                // fs.writeFileSync(`./fxImg/${num}`, res.text)
                fs.writeFile(`./GundamAvatar/${num}.gif`, res.body, (err) => {
                    if (err) {
                        console.log(`存储图片失败，编号${num}`)
                    }
                    console.log(`头像存储-${num}成功`)
                    console.log(`${i}条`)
                    getPic(++i)
                })
            }).catch(err => {
                console.log(`头像存储-${num}faile, again` + err);
                // fs.writeFileSync(`./GundamAvatar/errLog.log`, `头像存储-${num}faile`)
                logger.error(`头像存储-${num}faile`)
                if (err.status == 404) {
                    getPic(++i)
                } else {
                    getPic(i)
                }
            })
    }
    // robots.update(res)
    // console.log('更新tags完毕')
    // db.save()
}

function runProgramLogic2(robots) {
    let from_map = {},
        from_arr = [];
    let pilot_map = {},
        pilot_arr = []
    let force_map = {},
        force_arr = []
    let res = robots.find({})
    console.log(`已加载${res.length}条数据库内容`)
    res.forEach(gundam => {
        gundam.from = gundam.from.replace('出自作品:', '')
        if (!from_map[gundam.from]) {
            from_map[gundam.from] = true
            from_arr.push(gundam.from)
        }

        gundam.pilot = gundam.pilot.replace('驾驶员:', '')
        if (!pilot_map[gundam.pilot]) {
            pilot_map[gundam.pilot] = true
            pilot_arr.push(gundam.pilot)
        }
        gundam.force = gundam.force.replace('势力:', '')
        if (!force_map[gundam.force]) {
            force_map[gundam.force] = true
            force_arr.push(gundam.force)
        }
    });

    fs.writeFileSync('./filterMap.json', JSON.stringify({
        from_arr: from_arr,
        pilot_arr: pilot_arr,
        force_arr: force_arr
    }))
    console.log('write ok')

    robots.update(res)
    console.log('更新force完毕')
    db.save()
}

function runProgramLogic3(robots) {
    let res = robots.find({})
    console.log(`已加载${res.length}条数据库内容`)
    var count = 0
    res.forEach(ele => {
        // ele.tags.push(ele.model)
        // if (!ele.coding) {
        //     let code = Number(ele.ID).toString(16);
        //     if (code.length == 4) {
        //         ele.coding = code.slice(2, ).trim() + ' ' + code.slice(0, 2).trim()
        //     } else {
        //         console.log(ele.ID)
        //     }
        // }
        if (ele.coding) {
            count++;
            ele.coding = ele.coding.toUpperCase()
        }
    });



    console.log(count)
    robots.update(res)
    console.log('更新CODE完毕')
    db.save()
}
module.exports = db;